//
//  OAuthViewController.swift
//  weibo
//
//  Created by 叶子韬韬 on 2017/5/1.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavgationBar()
        
        //加载网页
        loadwebView()
        
    }

}
extension OAuthViewController{
    // MARK:- #注释>设置UI界面
    internal func setupNavgationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(OAuthViewController.fillItemClick))
        title = "登录"
    }
    
    internal func loadwebView (){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        //创建uri
        guard let url = URL(string: urlString)else{
            return
        }
        //加载webview
         webView.loadRequest(URLRequest(url: url))
        
    }
    
}
extension OAuthViewController{
    // MARK:- #注释>事件监听
    internal func closeItemClick(){
        dismiss(animated: true, completion: nil)
    }
    internal func fillItemClick(){
        
        let jsCode = "document.getElementById('userId').value='13407118674';document.getElementById('passwd').value='zl13407118674'"
        
        //webView执行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
}

// MARK:- #注释>webview的代理方法
extension OAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD .show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    //当准备加载某一个网页的时候会执行这个方法
    //返回true 标示继续加载  FALSE 表示不会继续加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        guard let url  = request.url else{
            return true
        }
        
        let stringUrl = url.absoluteString
        //判断stringUrl是否包含code
        guard stringUrl.contains("code=") else {
            return true
        }
        
        //将code截取出来
        let code = stringUrl.components(separatedBy: "code=").last!
        
        //请求AccessToken
        loadAccessToken(code: code)
        
        return false
    }
}

extension OAuthViewController{
    internal func loadAccessToken(code:String){
       NetworkTools.shareInstance.loadAccessToken(code: code) { (result, error) in
            if error != nil{
                print(error.debugDescription)
            }else{
               
                guard let accountDict = result else{
                    return
                }
                
                
                
                let account = UserAccount(dict: accountDict)
                
                //请求用户信息
                self.loadUserInfo(account: account)
            }
        
        
        }
    }
    //请求用户信息
    internal func loadUserInfo(account:UserAccount){
        guard let accout = account.access_token else{
            return
        }
        guard let uid = account.uid else{
            return
        }
        
        NetworkTools.shareInstance.loadUserInfo(access_token: accout, uid: uid) { (result, error) in
            if error != nil{
                print(error ?? "")
                return
            }
            guard let userInfoDict = result else{
                return
            }
            
            //把字典中的值赋给mode属性
            account.avatar_large = userInfoDict["avatar_large"] as? String
            account.screen_name = userInfoDict["screen_name"] as? String
            
         
            //将account保存
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccoutViewModel.shareInstance.accountPath)
            
            
            //将account设置到单例对象中
            UserAccoutViewModel.shareInstance.account = account
            
            // 退出当前控制器
            self.dismiss(animated: false, completion: {
                //显示欢迎界面
                UIApplication.shared.keyWindow?.rootViewController = WeclomeViewController()
                
            })
            
            
        }
    }
}
